package com.example.maoyanmovie.ui.fragment;

import android.content.Intent;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import com.example.maoyanmovie.base.BaseFragment;
import com.example.maoyanmovie.databinding.FragmentMineBinding;
import com.example.maoyanmovie.ui.activity.AboutActivity;
import com.example.maoyanmovie.ui.activity.LoginActivity;
import com.example.maoyanmovie.ui.activity.OrderListActivity;
import com.example.maoyanmovie.ui.activity.ProfileEditActivity;
import com.example.maoyanmovie.ui.activity.SettingsActivity;
import com.example.maoyanmovie.utils.Constants;
import com.example.maoyanmovie.utils.SPUtils;
import com.example.maoyanmovie.viewmodel.MineViewModel;

public class MineFragment extends BaseFragment<FragmentMineBinding, MineViewModel> {

    @Override
    protected FragmentMineBinding getViewBinding(LayoutInflater inflater, ViewGroup container) {
        return FragmentMineBinding.inflate(inflater, container, false);
    }

    @Override
    protected Class<MineViewModel> getViewModelClass() {
        return MineViewModel.class;
    }

    @Override
    protected void initView() {
        loadUserInfo();

        binding.ivEdit.setOnClickListener(v -> {
            startActivity(new Intent(getContext(), ProfileEditActivity.class));
        });

        binding.llOrders.setOnClickListener(v -> {
            startActivity(new Intent(getContext(), OrderListActivity.class));
        });

        binding.llSettings.setOnClickListener(v -> {
            startActivity(new Intent(getContext(), SettingsActivity.class));
        });

        binding.llAbout.setOnClickListener(v -> {
            startActivity(new Intent(getContext(), AboutActivity.class));
        });

        binding.btnLogout.setOnClickListener(v -> logout());
    }

    @Override
    protected void initData() {
        // No data to load
    }

    @Override
    protected void initObservers() {
        // No observers needed
    }

    private void loadUserInfo() {
        String username = SPUtils.getString(Constants.SP_KEY_USER_NAME, "未登录用户");
        String phone = SPUtils.getString(Constants.SP_KEY_USER_PHONE, "");

        binding.tvUsername.setText(username);
        binding.tvPhone.setText(phone);
    }

    private void logout() {
        SPUtils.putBoolean(Constants.SP_KEY_IS_LOGIN, false);
        SPUtils.remove(Constants.SP_KEY_USER_NAME);
        SPUtils.remove(Constants.SP_KEY_USER_PHONE);

        Intent intent = new Intent(getContext(), LoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
        if (getActivity() != null) {
            getActivity().finish();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        loadUserInfo();
    }
}
